<!-- 开发任务管理 -->
<script setup lang="ts">
defineOptions({
  name: 'Mission',
  inheritAttrs: false
});

import {
  getMissionPage,
  getMissionById,
  deleteMission,
  saveMission,
  updateMission,
  updateMissionStatus,
  exportMission
} from '@/api/mission';
import {
  MissionVO,
  MissionPageQuery,
  MissionFormType,
  MissionTypeNames,
  MissionPriorityNames,
  MissionStatusNames
} from '@/api/mission/types';
import { MISSION_TYPE, MISSION_PRIORITY, MISSION_STATUS } from '@/constants';
import { useUserStore } from '@/store/modules/user';
import { Plus, Download, Search, User, DataBoard, Grid, List } from '@element-plus/icons-vue';
import { useThrottleFn } from '@vueuse/core';
import OverviewTab from '@/components/Mission/OverviewTab.vue';
import KanbanTab from '@/components/Mission/KanbanTab.vue';
import TableTab from '@/components/Mission/TableTab.vue';
import MissionForm from '@/components/Mission/Form.vue';
import MissionPagination from '@/components/Mission/MissionPagination.vue';

const loading = ref(false); // 加载状态
const removeIds = ref<number[]>([]); // 删除任务ID集合 用于批量删除
const queryParams = reactive<MissionPageQuery>({
  pageNum: 1,
  pageSize: 10
});
const total = ref(0); // 数据总数
const pageData = ref<MissionVO[]>([]); // 任务数据
const activeTab = ref('overview'); // 激活的tab

// 按状态分组的任务数据
const missionsByStatus = ref<Record<number, MissionVO[]>>({
  [MISSION_STATUS.NOT_STARTED]: [],
  [MISSION_STATUS.IN_PROGRESS]: [],
  [MISSION_STATUS.COMPLETED]: [],
  [MISSION_STATUS.CLOSED]: []
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  title: ''
});

// 任务表单数据
const formData = reactive<MissionFormType>({
  missionTitle: '',
  missionDescription: '',
  missionType: MISSION_TYPE.NEW_FEATURE,
  priority: MISSION_PRIORITY.MEDIUM,
  status: MISSION_STATUS.NOT_STARTED,
  version: '',
  requirements: '',
  remarks: ''
});

const userStore = useUserStore();
const isAdmin = computed(() => userStore.roles.includes('ADMIN'));

// 状态列表配置
const statusTabs = [
  {
    value: 'overview',
    label: '总览',
    icon: DataBoard
  },
  {
    value: 'kanban',
    label: '看板',
    icon: Grid
  },
  {
    value: 'table',
    label: '表格',
    icon: List
  }
];

/** 查询 */
function handleQuery() {
  loading.value = true;
  getMissionPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
      groupMissionsByStatus();
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 按状态分组任务并按优先级排序 */
function groupMissionsByStatus() {
  // 清空分组
  missionsByStatus.value = {
    [MISSION_STATUS.NOT_STARTED]: [],
    [MISSION_STATUS.IN_PROGRESS]: [],
    [MISSION_STATUS.COMPLETED]: [],
    [MISSION_STATUS.CLOSED]: []
  };

  // 分组并排序
  pageData.value.forEach(mission => {
    if (mission.status && missionsByStatus.value[mission.status]) {
      missionsByStatus.value[mission.status].push(mission);
    }
  });

  // 按优先级排序（高>中>低）
  const priorityOrder = {
    [MISSION_PRIORITY.HIGH]: 1,
    [MISSION_PRIORITY.MEDIUM]: 2,
    [MISSION_PRIORITY.LOW]: 3
  };

  Object.keys(missionsByStatus.value).forEach(status => {
    missionsByStatus.value[Number(status)].sort((a, b) => {
      const priorityA = priorityOrder[a.priority || MISSION_PRIORITY.MEDIUM];
      const priorityB = priorityOrder[b.priority || MISSION_PRIORITY.MEDIUM];
      return priorityA - priorityB;
    });
  });
}

/** 重置查询 */
function resetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: MissionVO[]) {
  removeIds.value = selection.map(item => item.id!);
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型
 * @param id 任务ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true;

  if (type === 'mission-form') {
    // 任务表单弹窗
    if (id) {
      dialog.title = '修改任务';
      getMissionById(id).then(({ data }) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = '新增任务';
    }
  }
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  Object.assign(formData, {
    missionTitle: '',
    missionDescription: '',
    missionType: MISSION_TYPE.NEW_FEATURE,
    priority: MISSION_PRIORITY.MEDIUM,
    status: MISSION_STATUS.NOT_STARTED,
    version: '',
    requirements: '',
    remarks: ''
  });
  formData.id = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  const missionId = formData.id;
  loading.value = true;
  if (missionId) {
    updateMission(formData)
      .then(() => {
        ElMessage.success('修改任务成功');
        closeDialog();
        resetQuery();
      })
      .finally(() => (loading.value = false));
  } else {
    saveMission(formData)
      .then(() => {
        ElMessage.success('新增任务成功');
        closeDialog();
        resetQuery();
      })
      .finally(() => (loading.value = false));
  }
}, 3000);

/** 删除任务 */
function handleDelete(id?: number) {
  const missionIds = [id || removeIds.value].join(',');
  if (!missionIds) {
    ElMessage.warning('请勾选删除项');
    return;
  }

  ElMessageBox.confirm('确认删除任务?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function () {
    deleteMission(missionIds.split(',').map(Number)).then(() => {
      ElMessage.success('删除成功');
      resetQuery();
    });
  });
}

/** 更新任务状态 */
function handleStatusChange(row: MissionVO, newStatus: number) {
  console.log(row, newStatus);
  updateMissionStatus({
    id: row.id!,
    status: newStatus
  }).then(() => {
    ElMessage.success('状态更新成功');
    resetQuery(); // 重新加载数据
  });
}

/** 导出任务 */
function handleExport() {
  exportMission(queryParams).then((response: any) => {
    const fileData = response.data;
    const fileName = decodeURI(
      response.headers['content-disposition']?.split(';')[1]?.split('=')[1] || '开发任务列表.xlsx'
    );
    const fileType =
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8';

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement('a');
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="mission-container">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="header-left">
        <h1 class="page-title">开发任务管理</h1>
        <div v-if="!isAdmin" class="user-badge">
          <el-icon><user /></el-icon>
          <span>访客模式</span>
        </div>
      </div>
      <div class="header-actions">
        <el-input
          v-model="queryParams.missionTitle"
          placeholder="搜索任务..."
          :prefix-icon="Search"
          class="search-input"
          clearable
          @keyup.enter="handleQuery"
        />
        <el-button v-if="isAdmin" type="primary" :icon="Plus" @click="openDialog('mission-form')">
          新建任务
        </el-button>
        <el-button :icon="Download" @click="handleExport">导出</el-button>
      </div>
    </div>

    <!-- Tab导航 -->
    <div class="tab-navigation">
      <div class="tabs">
        <div
          v-for="tab in statusTabs"
          :key="tab.value"
          :class="['tab-item', { active: activeTab === tab.value }]"
          @click="activeTab = tab.value"
        >
          <el-icon class="tab-icon">
            <component :is="tab.icon" />
          </el-icon>
          <span>{{ tab.label }}</span>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 总览Tab -->
      <overview-tab v-if="activeTab === 'overview'" :missions="pageData" />

      <!-- 看板Tab -->
      <kanban-tab
        v-if="activeTab === 'kanban'"
        :missions-by-status="missionsByStatus"
        :is-admin="isAdmin"
        @status-change="handleStatusChange"
        @edit="openDialog('mission-form', $event.id)"
        @delete="handleDelete"
      />

      <!-- 表格Tab -->
      <table-tab
        v-if="activeTab === 'table'"
        :missions="pageData"
        :loading="loading"
        :is-admin="isAdmin"
        @selection-change="handleSelectionChange"
        @status-change="handleStatusChange"
        @edit="openDialog('mission-form', $event.id)"
        @delete="handleDelete"
      />

      <!-- 分页组件 -->
      <mission-pagination
        v-if="activeTab === 'table'"
        :total="total"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        @update:current-page="queryParams.pageNum = $event"
        @update:page-size="queryParams.pageSize = $event"
        @pagination="handleQuery"
      />
    </div>

    <!-- 任务表单弹窗 -->
    <mission-form
      v-model:form-data="formData"
      v-model:dialog-visible="dialog.visible"
      :dialog-title="dialog.title"
      :loading="loading"
      @submit="handleSubmit"
      @cancel="closeDialog"
    />
  </div>
</template>

<style scoped>
/* 任务管理页面样式 */

/* 容器样式 */
.mission-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
  overflow: hidden;
  min-width: 0;
}

/* 顶部标题栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: white;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.user-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #dbeafe 0%, #eff6ff 100%);
  border-radius: 20px;
  font-size: 14px;
  color: #1e40af;
  font-weight: 500;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 280px;
}

/* Tab导航 */
.tab-navigation {
  background: white;
  border-bottom: 1px solid #e5e7eb;
}

.tabs {
  display: flex;
  padding: 0 24px;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 24px;
  cursor: pointer;
  color: #6b7280;
  font-weight: 500;
  border-bottom: 3px solid transparent;
  transition: all 0.2s ease;
}

.tab-item:hover {
  color: #3b82f6;
  background: #f8fafc;
}

.tab-item.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
  background: #f8fafc;
}

.tab-icon {
  font-size: 18px;
}

/* 内容区域 */
.content {
  flex: 1;
  overflow: hidden;
  padding: 24px;
  width: 100%;
  min-width: 0;
}

/* 表单弹窗 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #f3f4f6;
}

/* 拖拽样式 */
.sortable-ghost {
  opacity: 0.4;
}

.sortable-drag {
  opacity: 0.8;
  transform: rotate(5deg);
}

/* 通用响应式设计 */
@media (max-width: 1200px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .search-input {
    width: 200px;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }

  .content {
    padding: 16px;
  }

  .tabs {
    padding: 0 16px;
    overflow-x: auto;
  }

  .tab-item {
    padding: 12px 16px;
    white-space: nowrap;
  }
}
</style>
